/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.view.statementView;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FileDialog;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.TableRowSorter;

import com.ruipengkj.ApplicationContext;
import com.ruipengkj.bean.TMoneyInOut;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.commons.base.query.PageIndex;
import com.ruipengkj.commons.base.query.PageModel;
import com.ruipengkj.commons.base.query.PageView;
import com.ruipengkj.commons.util.TabelUtil;
import com.ruipengkj.commons.util.Util;
import com.ruipengkj.commons.util.exportExcel.MoneyChargeOrPayExportUtil;
import com.ruipengkj.component.DataPackageComponent;
import com.ruipengkj.component.JLabelJComboBoxComponent;
import com.ruipengkj.component.RPJButtonBlue;
import com.ruipengkj.component.RPJButtonGray;
import com.ruipengkj.component.RPJButtonPrint;
import com.ruipengkj.component.jpanel.RPJPanelStatementTop;
import com.ruipengkj.component.page.PagingComponent;
import com.ruipengkj.model.StatementMoneyModel;
import com.ruipengkj.service.TBillDetailService;
import com.ruipengkj.service.TEmployeeService;
import com.ruipengkj.service.TMoneyInOutService;
import com.ruipengkj.view.base.BasePagePanel;
import com.ruipengkj.view.memberView.MemberFillCardPanel;
import com.ruipengkj.view.orderView.MarketReturnedAddOrModifyDialog;
import com.ruipengkj.view.orderView.OrderDetailDialog;
import com.ruipengkj.view.purchaseView.PurchaseEnterAddOrModifyPanel;
import com.ruipengkj.view.purchaseView.PurchaseRetreatAddPanel;

/**
 * 说明：
 * 应收款汇总表控制界面
 * @Author：黄盛强
 * @Date：2012-03-23
 */
public class StatementMoneyCharge extends BasePagePanel<TMoneyInOut> implements Runnable{
	private static final long serialVersionUID = 1L;
	private DataPackageComponent startTime;//开始日期
	private DataPackageComponent endTime; //结束日期
	
	private JLabelJComboBoxComponent type;//按类型查询
	
	private JButton selectButton;//选择
	private JButton clearButton;//清除按钮
	private JButton timeButton;//按时间分组
	private JButton personButton;//按付款人分组
//	private JButton printButton; //打印
	private JButton exportButton; //导出
//	private JButton exitButton; //退出
	
	private JTable table;//盘点盈余单汇总表TABLE
	private JScrollPane tableJsp;//盘点盈余单汇总表JScrollPane
	
	private PagingComponent pagingComponent;//翻页组件
	private PageView<TMoneyInOut> pageView;//翻页主键
	private PageModel pageModel;
	private TMoneyInOutService tMoneyInOutService;//资金进出service
	private StatementMoneyModel statementMoneyModel;
	private TBillDetailService tBillDetailService;
	private TEmployeeService tEmployeeService;
	private List<Integer> gross;//记录总金额所在的行
	public StatementMoneyCharge() {
		tMoneyInOutService = BuildSpringApplication.getInstance().getTMoneyInOutServiceImpl();
		tBillDetailService= BuildSpringApplication.getInstance().getTBillDetailServiceImpl();
		tEmployeeService= BuildSpringApplication.getInstance().getTEmployeeServiceImpl();
		gross = new ArrayList<Integer>();
		this.setLayout(new BorderLayout());
		this.init();
		this.initListener();
	}
	
	private void init() {
		pageView = new PageView<TMoneyInOut>();
		statementMoneyModel = new StatementMoneyModel(false);
		table=uiFactory.createRPJTable(statementMoneyModel, null, this, 30, JLabel.CENTER);
		tableJsp = new JScrollPane(table);
		
		this.setOpaque(true);
		this.setBackground(new Color(247, 252, 255));
		table.setOpaque(false);
		tableJsp.setOpaque(false);
		tableJsp.getViewport().setOpaque(false); 
		this.add(uiFactory.createFlowJPanel(), BorderLayout.WEST);
		this.add(uiFactory.createFlowJPanel(), BorderLayout.EAST);
		
		this.add(this.topPanel(),BorderLayout.NORTH);
		this.add(tableJsp,BorderLayout.CENTER);
		this.add(this.tailPanel(),BorderLayout.SOUTH);
		
		// 排序
		TableRowSorter<StatementMoneyModel> tableRowSorter = new TableRowSorter<StatementMoneyModel>(
				statementMoneyModel);
		table.setRowSorter(tableRowSorter);
	}
	
	private JPanel topPanel() {
		timeButton = new JButton("按时间分组");//按时间分组
		personButton = new JButton("按付款人分组");//按付款人分组
		type = new JLabelJComboBoxComponent("", new String[]{"所有类型", "采购退货收款", "销售收款", "充值收款"});
		JPanel jp1 = new RPJPanelStatementTop();
		startTime = new DataPackageComponent("开始日期", 15);
		endTime = new DataPackageComponent("结束日期", 15);
		selectButton = new RPJButtonBlue("查询");
		clearButton=new RPJButtonGray("清空");
		jp1.add(startTime);
		jp1.add(endTime);
		jp1.add(type);
		jp1.add(selectButton);
		jp1.add(clearButton);
		jp1.add(timeButton);
		jp1.add(personButton);
		
		return jp1;
	}

	private JPanel tailPanel() {
		JPanel tail_panel = uiFactory.createBorderJPanel();
		
		JPanel jp = uiFactory.createGridJPanel(1, 2);
		JPanel jp2 = uiFactory.createFlowJPanel(FlowLayout.LEFT);
		exportButton = new RPJButtonPrint("导 出");
		jp2.add(uiFactory.createJLabel("       "));
		jp2.add(exportButton);
		
		pagingComponent=new PagingComponent();
		pagingComponent.setPageDelegale(this);
		Util.setSize(pagingComponent, 80, 24);
		jp.add(jp2);
		jp.add(pagingComponent);
		
		tail_panel.add(jp);
		tail_panel.add(uiFactory.createFlowJPanel(), BorderLayout.NORTH);
		tail_panel.add(uiFactory.createFlowJPanel(), BorderLayout.SOUTH);
		return tail_panel;
	}

	private void initListener(){
		timeButton.addActionListener(this);
		personButton.addActionListener(this);
		selectButton.addActionListener(this);
		exportButton.addActionListener(this);
		clearButton.addActionListener(this);
	}
	
	//表格排序 加 计算总金额
	private void initGross(boolean type) {
		List<TMoneyInOut> tMoneyInOutList = statementMoneyModel.getTMoneyInOutList();
		if(tMoneyInOutList != null && tMoneyInOutList.size() != 0) {
			for (int i = gross.size() - 1; i >= 0; --i) {
				tMoneyInOutList.remove((int)gross.get(i));
			}
			
			gross.clear();
			statementMoneyModel.sort(type);
			for (int i = 0; i < tMoneyInOutList.size(); ++i) {
				String data;
				int money = 0;
				if (type) {
					data = tMoneyInOutList.get(i).getTime();
					for (int j = i; j < tMoneyInOutList.size() && data.equals(tMoneyInOutList.get(j).getTime()); ++j, ++i) {
						money += tMoneyInOutList.get(j).getGross();
					}
				
				} else {
					if(tMoneyInOutList.get(i).getPersonID() == null)
						tMoneyInOutList.get(i).setPersonID("");
					data = tMoneyInOutList.get(i).getPersonID();
					for (int j = i; j < tMoneyInOutList.size() && data.equals(tMoneyInOutList.get(j).getPersonID()); ++j, ++i) {
						money += tMoneyInOutList.get(j).getGross();
						if(j+1 < tMoneyInOutList.size() && tMoneyInOutList.get(j+1).getPersonID() == null)
							tMoneyInOutList.get(j+1).setPersonID("");
					}
				}
				gross.add(i);
				TMoneyInOut tMoneyInOut = new TMoneyInOut();
				tMoneyInOut.setTime("总额：" + money);
				tMoneyInOutList.add(i, tMoneyInOut);
			}
			
			table.updateUI();
		}
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == selectButton) {
			this.termQuery(1);
		} else if (e.getSource() == timeButton) {
			initGross(true);//按时间分组
		} else if (e.getSource() == personButton) {
			initGross(false);//按付款人分组
		}  else if(e.getSource()==exportButton){
			//导出
			FileDialog fileDialog = new FileDialog(new JDialog(), "文件导出",FileDialog.SAVE);
			fileDialog.setVisible(true);
			String fileDir = fileDialog.getDirectory();
			String fileName = fileDialog.getFile();
			if (fileDir != null && !fileDir.equals("") && fileName != null&& !fileName.equals("")) {
				if (!fileName.toLowerCase().endsWith(".xls")) {
					if (fileName.lastIndexOf(".") != -1) {
						fileName = fileName.substring(0, fileName.lastIndexOf("."))+ ".xls";
					} else {
						fileName = fileName + ".xls";
					}
				}
				try {
					List<TMoneyInOut> list = tMoneyInOutService.findExportService(this.queryTerm());
					if (list != null && list.size() != 0) {
						exportButton.setEnabled(false);
						MoneyChargeOrPayExportUtil.writeExcel(fileDir + fileName,list, true,tBillDetailService,tEmployeeService);
						JOptionPane.showMessageDialog(null, "导出成功");
					} else {
						JOptionPane.showMessageDialog(null, "数据为空，导出失败");
					}
				} catch (Exception e1) {
					e1.printStackTrace();
					JOptionPane.showMessageDialog(null, "导出失败");
				}
				exportButton.setEnabled(true);
			}
		} else if (e.getSource() == clearButton) {
			startTime.setDate(null); //时间1
			endTime.setDate(null); //时间2
			type.getBox().setSelectedIndex(0);
		}
	}
	
	@Override
	public void run() {
		this.termQuery(1);
	}
	
	private TMoneyInOut queryTerm(){
		TMoneyInOut tMoneyInOut=new TMoneyInOut();
		tMoneyInOut.setHappenTime(startTime.getDate());
		tMoneyInOut.setEndTime(endTime.getDate());
		tMoneyInOut.setType(ApplicationContext.MONEYINOUT_TYPE_IN);
		switch(type.getBox().getSelectedIndex()) {
		//"所有类型", "采购退货收款", "销售收款", "充值收款"
		//1为采购引起的出款 2为采购退货引起收款3为销售引起的收款 4为销售退货引起的出款 5为充值收款 10为费用单
		case 1:
			tMoneyInOut.setSourceType(ApplicationContext.MONEYINOUT_SOURCE_TYPE2);
			break;
		case 2:
			tMoneyInOut.setSourceType(ApplicationContext.MONEYINOUT_SOURCE_TYPE3);
			break;
		case 3:
			tMoneyInOut.setSourceType(ApplicationContext.MONEYINOUT_SOURCE_TYPE5);
			break;
		}
		return tMoneyInOut;
	}
	
	//条件查询
	@Override
	protected void termQuery(final int currentPage){
		new Thread(){
			public void run(){
				tableJsp.getViewport().remove(table);
				tableJsp.getViewport().add(waitComponent);
				try {
					pageView.setCurrentPage(currentPage);
					PageModel<TMoneyInOut> pageModel = tMoneyInOutService.getScrollListService(pageView.getFirstResult(), pageView.getMaxResult(),queryTerm());
					pageView.setPageModel(pageModel);
					pageView.setPageIndex(PageIndex.getPageIndex(pageView.getPageCode(), pageView.getCurrentPage(), pageView.getTotalPage()));
						TabelUtil.clearTableRowSorter(table);
				if(pageModel!=null){
						statementMoneyModel.setRowData(pageModel.getResultList());
						SwingUtilities.invokeLater(new Runnable() {
							@Override
							public void run() {
								tableJsp.getViewport().remove(waitComponent);
								tableJsp.getViewport().add(table);
								TabelUtil.setJTabelAutoClumnWidth(table);
								pagingComponent.show();
							}
						});
						
						
					}else{
						//没有订单数据
						tableJsp.getViewport().remove(waitComponent);
						tableJsp.getViewport().add(table);
						statementMoneyModel.clear();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}
	@Override
	protected PageView<TMoneyInOut> getPageView() {
		return pageView;
	}
	
	public void mouseClicked(MouseEvent e) {
		// 鼠标按键在组件上单击（按下并释放）时调用。
		if (e.getSource() == table) {
			if (e.getClickCount() == 2) {//鼠标双击时
				TMoneyInOut tMoneyInOut = statementMoneyModel.getTMoneyInOut(table.getSelectedRow());
				String id = tMoneyInOut.getSource();
				switch (tMoneyInOut.getSourceType()) {
				//出入原因类型TINYINT  1为采购引起的出款 2为采购退货引起收款3为销售引起的收款
				//4为销售退货引起的出款 5为充值收款 10为费用单 
					case 1:
						new PurchaseEnterAddOrModifyPanel(null, "进货单详细", true).showDialog(id);
						return;
					case 2:
						new PurchaseRetreatAddPanel(null, "退货单详细", true).showDialog(id);
						return;
					case 3:
						OrderDetailDialog orderDetailDialog = new OrderDetailDialog(null, "销售订单详情", true);
						orderDetailDialog.showDialog(id);
						return;
					case 4:
						new MarketReturnedAddOrModifyDialog(null, "销售退货详情", true).showDialog(id);
						return;
					case 5:
						new MemberFillCardPanel().showDialog(id);
						return;
					case 10:
						return;
				}
			}
		}
	}

	@Override
	public void clear() {
		// TODO Auto-generated method stub
		
	}
}
